import { ref, computed } from 'vue'
import { useIntervalFn } from '@vueuse/shared'
import dayjs from 'dayjs'
/**
 * 倒计时逻辑函数封装
 * @param {Number} {time} 倒计时秒数
 * @returns {Object} { start, pause, countTime, resume,countTimeText }
 * */
export const useInterval = (time = 60) => {
  const countTime = ref(0)
  // 在useIntervalFn函数里有两个参数，一个是开始，一个是暂停
  const { resume, pause } = useIntervalFn(() => {
    countTime.value--
    if ((countTime.value <= 0)) {
      pause()
    }
    // //console.log('计时器正在执行。。。。')
  }, 1000, { immediate: false })
  const start = (newTime) => {
  // 在计时器开始的时候重新赋值给定时器开始计时
    countTime.value = newTime || time
    resume()
  }
  const countTimeText = computed(() => {
    return dayjs.unix(countTime.value).format('mm分ss秒')
  })
  return { start, pause, countTime, resume, countTimeText }
}
